package com.yupi.springbootinit.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description
 * @Author minify
 * @Date 2023/12/19 21:21
 * @Project mybi-backend
 */
public class DirectConsumer {

    private static final String EXCHANGE_NAME = "direct_exchange";


    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();
        // 声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        // 声明队列
        String queueName = "xiaozhang";
        channel.queueDeclare(queueName, true, false, false, null);
        // 绑定队列和交换机
        channel.queueBind(queueName, EXCHANGE_NAME, "info");
        // 声明队列
        String queueName1 = "xiaowang";
        channel.queueDeclare(queueName1, true, false, false, null);
        // 绑定队列和交换机
        channel.queueBind(queueName1, EXCHANGE_NAME, "error");

        DeliverCallback xiaozhang = (consumerTag, message) -> {
            try {
                System.out.println("xiaozhang:" + new String(message.getBody()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        DeliverCallback xiaowang = (consumerTag, message) -> {
            try {
                System.out.println("xiaowang:" + new String(message.getBody()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        // 监听队列
        channel.basicConsume(queueName, false, xiaozhang, consumerTag -> {
        });
        channel.basicConsume(queueName1, false, xiaowang, consumerTag -> {
        });
    }
}
